package com.dhl.cloud.common.util;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import com.dhl.cloud.course.entity.LessionTranscriptmut;

public class WordUtil {

	 /**
     * 导出word
     * <p>第一步生成替换后的word文件，只支持docx</p>
     * <p>第二步下载生成的文件</p>
     * <p>第三步删除生成的临时文件</p>
     * 模版变量中变量格式：{{foo}}
     *
     * @param sourcePath word模板路径
     * @param targetPath 生成文件路径
     * @param params     替换的参数
     */
    public static void exportWord(String sourcePath, /*String targetPath,*/List<LessionTranscriptmut> list) {
        BufferedOutputStream fos = null;
        try {
        	
        	File file = new File(sourcePath);
        	if (file.exists())
        	{
        		InputStream is = new FileInputStream(sourcePath);
        		XWPFDocument doc = new XWPFDocument(is);
        		// 清除所有内容
                clearContent(doc);
                is.close();
        	}
//        	XWPFDocument doc = WordExportUtil.exportWord07(sourcePath, params);
        	// 创建一个新的Word文档
            XWPFDocument doc = new XWPFDocument();
        	for (LessionTranscriptmut lessionTranscript : list) {
                // 创建一个段落
                XWPFParagraph paragraph = doc.createParagraph();
                XWPFRun run = paragraph.createRun();
                run.setText(lessionTranscript.getEncontent());
                XWPFParagraph paragraph2 = doc.createParagraph();
                XWPFRun run2 = paragraph2.createRun();
                run2.setText(lessionTranscript.getContent());
        	}
            
            fos = new BufferedOutputStream(new FileOutputStream(sourcePath));
            doc.write(fos);
            doc.close();
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
    private static void clearContent(XWPFDocument doc) {
    	// 获取文档的body元素
        List<XWPFParagraph> paragraphs = doc.getParagraphs();
        for (int i = paragraphs.size() - 1; i >= 0; i--) {
            // 从文档中删除段落
            doc.removeBodyElement(i);
        }
    }

}

